<template>
	<view class="login-page" :style="backgroundStyle">
		<view class="card-box">
			<view class="login-input-box">
				<view class="iconfont  icon-zhanghu1" :class="[theme]"></view>
				<input v-model="username" class="login-input username-input" placeholder="请输入您的账户"
					:focus="curFocusId == 'userFocus'" @focus="handleFocus('userFocus')" @blur="handleBlur"
					@confirm="handleConfirm" placeholder-class="input-placeholder" />
				<icon type="clear" size="14" color="#666666" @click="clearIcon('userFocus')" style="margin: auto;"
					v-if="curFocusId == 'userFocus'" />
			</view>
			<view class="login-input-box password-input" :class="[theme]">
				<view class="iconfont icon-mima1"></view>
				<input v-model="password" class="login-input" placeholder="请输入您的密码" :password="showPassword"
					:cursor="password.length" :focus="curFocusId == 'passwordFocus'"
					@focus="handleFocus('passwordFocus')" @blur="handleBlur" @confirm="bindLogin"
					placeholder-class="input-placeholder" />
				<icon type="clear" size="14" color="#666666" @click="clearIcon('passwordFocus')" style="margin: auto;"
					v-if="curFocusId == 'passwordFocus'" />
				<view class="last-font iconfont icon-chakan eye-icon" :class="[!showPassword ? 'eye-active' : '']"
					@click="changePassword"></view>
			</view>
			<view class="privacy-policy" @click="onPrivacyPolicies" :class="[theme]">查看《隐私政策》</view>
			<eui-button type="base" @buttonClick="CheckIsInsertCode" title="立即登录" class="login-btn" />
			<view class="set-btn" @click="onClickSetCode">设置客户代码</view>
			<view class="tips">
				<view class="flex justify-content-center">欢迎使用<b>{{note}}</b>移动管理平台</view>
				<view>©2012-2024昂捷信息·技术支持</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, computed } from 'vue';
	import { onReady, onShow } from '@dcloudio/uni-app';
	import apps from '../app';
	import service from '../../../common/service';
	import enjoy from '../../../common/enjoy.js'
	import { storeToRefs } from 'pinia';
	import { useMainStore } from '../../../store/modules/store';
	import { useLoginStore } from '../../../store/modules/useLoginStore';
	import { useThemeStore } from '../../../store/themeStore';
	import { useParamStore } from '@/store/useParamStore';
	import { useModuleDataStore } from '@/store/useModuleDataStore';
	import EuiButton from '@enjoy/mobile/components/button/button.vue';

	const mainStore = useMainStore();
	const LoginStore = useLoginStore();
	const themeStore = useThemeStore(); // 主题
	const ParamStore = useParamStore();
	const { theme } = storeToRefs(themeStore);
	const backgroundStyle = computed(() => {
		const baseUrl = `${LoginStore.ImageBaseUrl}/xcxStatic/img`;
		const _theme = theme.value.replace(/-(\w)/g, (match, letter) => letter.toUpperCase());
		return {
			backgroundImage: `url(${baseUrl}/${_theme}/login.png)`
		};
	});
	// 账号密码
	let username = ref('');
	let password = ref('');
	// 焦点
	const curFocusId = ref('');
	const FocusConfirm = ref(false);

	// 系统参数
	let note = ref('');
	let isDevtools = ref(false);
	let frequency = ref(0);
	let isOpenVerify = ref(false); // 管e通登录时是否开启验证码功能
	let isVerifyTime = ref(''); // 管e通登录时连续失败N次后需要验证码
	let isNeedVerify = ref(false); // 调用接口判断是不是需要验证码

	// 初始化
	const initProvider = () => {
		let customerObject = service.getStorageSync("CUSTOMEROBJECT");
		if (!customerObject) {
			uni.reLaunch({
				url: '../reg/reg'
			});
		} else {
			note.value = customerObject.EnjoyMain.c_name || '';
			let login_data = apps.getStorageSync('login_data');
			if (login_data) {
				username.value = login_data.sUser;
				password.value = login_data.sPassword;
			}
		}
	}

	const CheckIsInsertCode = async (e : Event) => {
		// e.preventDefault();
		if (isNeedVerify.value || (isOpenVerify.value && parseFloat(isVerifyTime.value) === 0)) {
			verifyFasong();
		} else {
			bindLogin();
		}
	};
	// 启动校验功能, 拖动托盘到指定位置
	const verifyFasong = () => {
		// this.$refs.verifyElement.show();
	}
	// 点击登录
	const bindLogin = () => {
		if (username.value.length < 1) {
			service.enjoyShowToast('请输入用户编码')
			return;
		}
		if (password.value.length < 1) {
			service.enjoyShowToast('请输入密码')
			return;
		}
		/**
		 * 下面简单模拟下服务端的处理
		 * 检测用户账号密码是否在已注册的用户列表中
		 * 实际开发中，使用 uni.request 将账号信息发送至服务端，客户端在回调函数中获取结果信息。
		 */
		toServiceClear();
		let ObjectData = {
			sTenantId: '',
			sUser: username.value,
			sPassword: password.value,
			sIMSI: '', //window.localStorage['DeviceImsi'], //给手机唯一标识
			sDeviceType: '', //window.localStorage['sDeviceType'],
			sDeviceName: '', //window.localStorage['sDeviceName'],
			access_token: '',
			sSerial: service.getDeviceInfo().deviceId,
		};
		service.enjoyShowLoading('正在登录...');
		apps.MobileLoginNew(ObjectData, res => {
			if (res.HasException) {
				if (res.ObjectData && res.ObjectData.CheckType && res.ObjectData.CheckType == '验证码') {
					isNeedVerify.value = true;
				}
				if (res.Exception.Message) {
					// console.log(JSON.stringify(res), this.frequency);
					service.enjoyShowToast(res.Exception.Message)
					service.enjoyHideLoading();
				}
			} else {
				// console.log(104, '________登录成功___________');
				service.enjoyHideLoading();
				if (res.ObjectData) {
					if (res.ObjectData && res.ObjectData.CheckType && res.ObjectData.CheckType == '验证码') {
						isNeedVerify.value = true;
					}
					let customerObject = service.getStorageSync("CUSTOMEROBJECT");
					service.setStorageSync('MobileServiceAddress', JSON.stringify(customerObject.EnjoyMain.c_mobile_service_ip))
					const loginInfo = res.ObjectData;
					username.value = loginInfo.sUser;
					const UserState = res.UserState;

					//成功之后需要重置用户
					ObjectData.sUser = loginInfo.sUser;
					ObjectData.access_token = loginInfo.idsToken ? loginInfo.idsToken.access_token : '';
					ObjectData.sTenantId = loginInfo?.idsToken?.tenantid || '';
					//写入状态
					mainStore.loginInfoin(loginInfo);

					if (res.ObjectData.sIsInitPwd == '是') {
						LoginJump(loginInfo, ObjectData, UserState, false);
						if (customerObject.EnjoyMain.c_mobile_service_ip) {
							const self = this;
							uni.showModal({
								title: ' 提示',
								content: '您使用的是初始密码，请修改密码!',
								showCancel: true,
								confirmText: '去修改密码',
								success: (res) => {
									if (res.confirm) {
										service.setStorageSync('_loginUser', loginInfo.sUser)
										uni.navigateTo({
											url: '/packages/MainViews/user/changePassword?nagviFlag=login',
										});
									}
								}
							});
						} else {
							service.enjoyShowToast('主应用地址获取错误,请重新配置客户代码')
						}
					} else {
						LoginJump(loginInfo, ObjectData, UserState, true);
					}
				}
			}
		}, (err) => {
			if (frequency.value == 2) {
				service.enjoyHideLoading();
				updateReg();
			} else if (frequency.value == 5) {
				uni.showToast({
					duration: 3500,
					icon: 'none',
					title: err,
					mask: true,
				});
				uni.reLaunch({
					url: '../reg/reg'
				});
				service.enjoyHideLoading();
			} else {
				bindLogin();
			}
			frequency.value = frequency.value + 1;
		})
	}
	// 登录之后跳转
	const LoginJump = async (login, ObjectData, UserState, CanToMainPage) => {
		//获取参数值
		await GetSyscfgOfTask();
		//重置登录状态
		apps.setStorageSync('bTokenExpired', 'false');
		// console.log('LoginJump--------', JSON.stringify(login));
		if (!login.bLogin) {
			service.enjoyShowToast(login.sErrInfo)
		} else {
			if (!login.sWarning) {
				service.enjoyShowToast(login.sWarning)
			}
			loginLocal(login.sUserName, ObjectData, UserState, CanToMainPage);

			//注册App消息推送
			// #ifdef APP
			setTimeout(() => {
				OperatePushReg()
			}, 400);
			// #endif
		}

		// 兼容老版本处理 app.
		apps.addlocalStorage('$state', login);
		apps.setStorageSync('$state', login);
		try {
			mainStore.loginInfoin(login);
			apps.setEnjoyServiceIp((data : any) => {
				mainStore.enjoyServiceIpin(data);
				LoginStore.updateEnjoyIp(data);
			})
		} catch (e) {
			//TODO handle the exception
		}
		GetSyscfg();
		GetMyMenu();
	};
	// 注册App消息推送
	const OperatePushReg = () => {
		let info, ClientId = '',
			pushstr = '',
			sDeviceName = '',
			sDeviceTypeName = 'Android';
		let push = plus.push;

		if (push != undefined && push != '' && push != null) {
			info = push.getClientInfo();
		}

		if (info != undefined && info != '' && info != null) {
			ClientId = info.clientid;
		}
		//注册成功才处理
		if (ClientId) {
			sDeviceTypeName = plus.os.name != "iOS" ? 'Android' : 'IOS';
			//当两台ios设备使用相同apple账号时获取到的uuid是相同的，加上型号以区分
			sDeviceName = sDeviceTypeName == 'IOS' ? (plus.device.model + '&&' + plus.device.uuid) : plus.device.uuid;

			pushstr = 'device:' + JSON.stringify(plus.device) + 'os:' + JSON.stringify(plus.os) + 'ios：' + JSON.stringify(plus.ios);

			const ObjectData = {
				sUser: username.value,
				sMiPushID: ClientId,
				sDeviceType: sDeviceTypeName,
				sDeviceName: sDeviceName,
				sComment: pushstr,
				flag: 'login'
			}
			apps.OperatePushReg(ObjectData, (res) => {
				if (res.HasException && res.Exception.Message) {
					uni.showToast({
						duration: 3500,
						icon: 'none',
						title: res.Exception.Message,
						mask: true,
					});
				}
			}, () => {
				//失败时忽略处理
			});
		}
	}
	const updateReg = () => {
		/**
		 * 更新客户代码
		 */
		const CUSTOMEROBJECT = service.getStorageSync("CUSTOMEROBJECT");
		let customerObject = CUSTOMEROBJECT ? CUSTOMEROBJECT : {};
		let customerNo;
		if (customerObject && customerObject.ID) {
			customerNo = customerObject.ID;
		}
		if (customerNo.length <= 0) {
			service.enjoyShowToast('客户代码不能为空！')
			return;
		}
		const AmapArray = service.getStorageSync('MobileAmap')
		if (customerNo != 'EIInnerNet') {
			// console.log(customerNo);
			const ObjectData = {
				IsNotPage: true,
				SqlWhereTail: " where c_cloud_id = '" + customerNo + "' ",
				Tag: AmapArray
			}
			apps.GetCloudCustDef(ObjectData, (res) => {
				service.setStorageSync('MobileAmap', JSON.stringify([]))
				// console.log(JSON.stringify(res))
				let listObj = {
					EnjoyMain: null
				};
				if (res && res.ObjectData && res.ObjectData.ReturnObject) {
					let ReturnObject = res.ObjectData.ReturnObject;
					for (let i in ReturnObject) {
						let item = ReturnObject[i];
						listObj.ID = item.c_cloud_id;
						if (item.c_ismain_app === "是") {
							// console.log(item)
							listObj.EnjoyMain = {
								...item,
								c_mobile_service_ip: item.c_mobile_service_ip + '/mbmv5',
							};
						}
						listObj[item.c_application] = {
							...item
						};
					}
				}
				if (listObj.EnjoyMain) {
					let customerObject = listObj;
					let customerList = [];
					customerList.push(listObj);
					customerList = enjoy.uniqueArray(customerList, 'ID');
					service.setStorageSync("CUSTOMERLIST", customerList);
					service.setStorageSync("CUSTOMEROBJECT", customerObject);
					LoginStore.setCustomer(customerObject);
				}
				bindLogin();
			}, (err) => {
				uni.showToast({
					title: `获取客户配置失败-Login!`,
					duration: 3500,
					icon: 'none',
				})
				//更新获取失败时还是继续用原来的地址尝试登录
				bindLogin();
			});
		} else {
			service.setStorageSync('MobileAmap', JSON.stringify([]));
			//离线不使用云端配置时，直接用本地地址
			//更新获取失败时还是继续用原来的地址尝试登录
			bindLogin();
		}
	};
	const loginLocal = (nickName, loginData, uniIdToken, CanToMainPage) => {
		console.log('loginLocal', loginData);
		apps.setStorageSync('login_type', 'local');
		apps.setStorageSync('username', nickName);
		apps.setStorageSync('login_data', loginData);
		apps.setStorageSync('uniIdToken', uniIdToken);
		apps.addlocalStorage('uniIdToken', uniIdToken);
		//能否登录后进入主页，若是初始密码时是不能跳的
		if (CanToMainPage == true) {
			toMain(nickName);
		}
	};
	const onClickSetCode = (e : Event) => {
		e.preventDefault();
		uni.navigateTo({
			url: '../reg/reg'
		});
	};

	// 系统参数
	const GetSyscfgByLogin = () => {
		service.enjoyShowLoading('正在获取系统参数配置...');
		var req = mainStore.enjoyServiceIp;
		apps.GetSyscfgByLogin(req, res => {
			service.enjoyHideLoading();
			if (!res.HasException && res.ObjectData) {
				if (res.ObjectData && res.ObjectData.ReturnObject) {
					var list = res.ObjectData.ReturnObject;
					for (var i = 0; i < list.length; i++) {
						if (list[i].c_name == '管e通登录时是否开启验证码功能') {
							isOpenVerify.value = list[i].c_value == '是' ? true : false;
						}
						if (list[i].c_name == '管e通登录时连续失败N次后需要验证码') {
							isVerifyTime.value = list[i].c_value
						}
					}
				}
			} else {
				service.enjoyShowToast('获取系统配置错误，原因：' + res.Exception.Message)
			}
		}, (err) => {
			service.enjoyHideLoading();
			console.log(err)
		})
	}

	// 获取菜单
	const moduleDataStore = useModuleDataStore();
	const GetMyMenu = () => {
		let request = {
			url: LoginStore.EnjoyMain,
			data: {
				UniqueKey: "管易通40公共",
				ObjectData: mainStore.loginInfo?.sUser && mainStore.loginInfo?.sUser != '' && mainStore.loginInfo?.sUser !=
					null ? mainStore.loginInfo?.sUser : '0720', //用于苹果审核特殊处理获取不到用户时默认按0006账号获取
				MethodName: "GetMyMenu",
			},
		}
		service.request(request, (res) => {
			if (res && res.data) {
				if (!res.data.HasException) {
					const menus = res.data.ObjectData || [];
					moduleDataStore.setMenusAndLimitCode(menus);
				} else {
					service.enjoyShowToast(res.data.Exception.Message)
				}
			}
		}, () => {
			console.log('失败')
		});
	}
	// 任务参数
	const GetSyscfgOfTask = async () => {
		service.enjoyShowLoading('正在获取系统参数配置...');
		let req = mainStore.enjoyServiceIp;
		apps.GetSyscfgOfTask(req, res => {
			service.enjoyHideLoading();
			if (!res.HasException && res.ObjectData) {
				if (res.ObjectData && res.ObjectData.ReturnObject) {
					let list = res.ObjectData.ReturnObject;
					let taskData = list.find(x => x.c_name === '是否启用任务管理')
					if (taskData) {
						ParamStore.setShowTaskModule(taskData.c_value === '1');
					}
				}
			} else {
				service.enjoyShowToast('获取系统配置错误，原因：' + res.Exception.Message)
			}
		}, (err) => {
			service.enjoyHideLoading();
			console.log(err)
		})
	}

	// 系统参数
	const GetSyscfg = () => {
		service.enjoyShowLoading('正在获取系统参数配置...');
		var req = mainStore.enjoyServiceIp;
		//若后台是Mall系统没有RMIS系统时不会有RMIS地址，这时会导致接口调用失败提示登录失效的问题
		if (req.EnjoyRMIS && req.EnjoyRMIS != '') {
			apps.GetSyscfgGoodsLength(req, (res) => {
				service.enjoyHideLoading();
				if (!res.HasException && res.ObjectData) {
					if (res.ObjectData.ReturnObject.length > 0) {
						var length = res.ObjectData.ReturnObject[0].c_value;
						service.setStorageSync('goods_length', length)
					}
				} else {
					service.enjoyShowToast('获取系统配置错误，原因：' + res.Exception.Message)
				}
			}, err => {
				service.enjoyHideLoading();
				console.log(err)
			})
		}
	}

	const toMain = (userName) => {
		mainStore.login();
		/**
		 * 强制登录时使用reLaunch方式跳转过来
		 * 返回首页也使用reLaunch方式
		 */
		if (mainStore.forcedLogin) {
			uni.getSystemInfo({
				success: function (res) {
					// TODO
					// console.log(426, '_______________', res);
				}
			})
			setTimeout(() => {
				uni.reLaunch({
					url: '/packages/MainViews/main/main?type="login"',
				});
			}, 800);
		} else {
			uni.navigateBack();
		}

	};
	const toServiceClear = () => {
		apps.addlocalStorage('uniIdToken', '');
	}

	// 隐私跳转
	const onPrivacyPolicies = () => {
		uni.navigateTo({
			url: '/packages/MainViews/main/pravicypolicies'
		});
	};

	onShow(() => {
		let login_data = apps.getStorageSync('login_data');

		let sUser = '';
		if (login_data) {
			sUser = login_data.sUser;
		}
		if (sUser) {
			isNeedVerify.value = false;
			apps.CheckIsInsertCode(sUser, (res) => {
				if (res.HasException) {
					if (res.Exception.Message) {
						service.enjoyShowToast(res.Exception.Message)
						service.enjoyHideLoading();
					}
				} else {
					if (res.ObjectData == '') { } else {
						// 需要输入验证码
						isNeedVerify.value = true;
					}
					service.enjoyHideLoading();
				}
			}, () => { });
		}
	})
	onReady(() => {
		initProvider();
		GetSyscfgByLogin();
		isDevtools.value = uni.getSystemInfoSync().platform === 'devtools';
	})

	// 切换密码显示隐藏
	const showPassword = ref(true);
	const changePassword = () => {
		showPassword.value = !showPassword.value;
		curFocusId.value = "";
		setTimeout(() => {
			curFocusId.value = 'passwordFocus';
		}, 0)
	}

	// 焦点进入
	const handleFocus = (val : string) => {
		setTimeout(() => {
			curFocusId.value = val;
		}, 400)
	}
	// 失去焦点
	const handleBlur = () => {
		setTimeout(() => {
			curFocusId.value = '';
			if (FocusConfirm.value) {
				curFocusId.value = 'passwordFocus';
				FocusConfirm.value = false;
			}
		}, 100)
	};
	// 清空内容
	const clearIcon = (val : string) => {
		if (val == 'userFocus') {
			username.value = '';
		} else {
			password.value = '';
		}
		curFocusId.value = "";

		setTimeout(() => {
			curFocusId.value = val;
		}, 300)
	}
	// 输入账号回车
	const handleConfirm = () => {
		if (username.value) {
			FocusConfirm.value = true;
		}
	}
</script>

<style scoped lang="scss">
	.login-page {
		position: relative;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		width: 100%;
		height: 100vh;
		background-repeat: no-repeat;
		background-position: top left;
		background-size: 750rpx 480rpx;
		box-sizing: border-box;
		background-color: $enjoy-bg-color;
		font-family: PingFangSC, PingFang SC;

		.login-btn {
			width: 440rpx;
			height: 88rpx;
			margin: 40px 0 30px 50%;
			transform: translate(-50%);
			display: flex;
			align-items: center;
			justify-content: center;
			padding-top: 0px;
		}
	}

	.card-box {
		position: absolute;
		left: 10px;
		bottom: 10px;
		padding: 52rpx 40rpx 40rpx;
		margin-right: 10px;
		width: calc(100% - 20px);
		height: calc(100% - 204px);
		background: $enjoy-white-color;
		border-radius: 20px 20px 10px 10px;
		box-sizing: border-box;
	}

	.login-input-box {
		display: flex;
		justify-content: flex-start;
		align-content: center;

		height: 98rpx;
		padding: 12rpx 28rpx;
		box-sizing: border-box;
		background: $enjoy-card-slot-bg-color;
		border-radius: 100rpx;

		view {
			font-size: 20px;
			width: 80rpx;
			height: 74rpx;
			text-align: center;
			line-height: 74rpx;
			color: var(--theme-color);
		}

		.last-font {
			width: auto;
			padding-left: 20rpx;
			font-size: 40rpx;
			font-size: 28rpx;
		}

		.login-input {
			width: 0;
			flex: 1;
			height: 100%;
			margin-left: 10px;
		}

		.input-placeholder {
			color: $enjoy-color-hint;
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			font-size: 28rpx;
		}

		.icon-guanbi11 {
			color: $enjoy-color-subtitle;
		}

		.eye-icon {
			font-size: 40rpx;
			color: $enjoy-color-subtitle;
		}

		.eye-active {
			color: var(--theme-color);
		}

		.clear-icon {
			width: auto;
			font-size: 14px;
		}
	}

	.password-input {
		margin-top: 16px;
	}

	.privacy-policy {
		width: 100%;
		margin: 24rpx auto 0;
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		font-size: 24rpx;
		text-align: center;
		color: var(--theme-color);
	}

	.set-btn {
		margin: auto;
		width: 300rpx;
		height: 68rpx;
		color: $enjoy-color-subtitle;
		text-align: center;
		border-radius: 34rpx;
		border: 2rpx solid $enjoy-color-split;
		font-family: PingFangSC, PingFang SC;
		line-height: 68rpx;
		font-size: 26rpx;
	}

	.tips {
		position: absolute;
		bottom: 20px;
		width: calc(100% - 40px);
		padding: 0 32px;
		color: $enjoy-color-hint;
		font-size: 20rpx;
		text-align: center;
		font-family: PingFangSC, PingFang SC;
		word-break: break-all;
		box-sizing: border-box;
		line-height: 34rpx;
		display: flex;
		flex-direction: column;
	}

	.flex {
		display: flex;
	}

	.justify-content-center {
		justify-content: center;
	}
</style>